import { createEffect, Signal } from "solid-js";
import createModel from "./utils/createModel";

export interface PinFieldProps {
    type?: string;
    inputMode?:
    | "numeric"
    | "tel"
    | "text"
    | "none"
    | "url"
    | "email"
    | "decimal"
    | "search";
    onBackspace?(index: number): void;
    index: number;
    currentIndex: number;
    onChange(v: string, index: number): void;
    onPaste?(value: string | undefined): void;
    value: Signal<string>;
    validate(value: string):string;
    disabled?: boolean;
}
export function PinField(props: PinFieldProps) {
    const type = () => (props.type === "numeric" ? "tel" : props.type ?? "text");
    const inputMode = () => props.inputMode ?? "text";

    let el: any;
    const [value, setValue] = createModel(props, "value", "");

    const autoFocus = () => {
        return props.currentIndex === props.index;
    };

    createEffect(() => {
        if (props.currentIndex === props.index) {
            el.focus();
        } else {
            el.blur();
        }
    });
    const onKeyDown = (e: KeyboardEvent) => {
        if (e.code === "Backspace" && (!value() || !value().length)) {
            props.onBackspace && props.onBackspace(props.index);
        }
    };

    const onChange = (e: Event) => {
        let v = (e.target as HTMLInputElement).value;
        v = v.substring(0, 1);
        v = props.validate(v);
        el.value = v;
        setValue(v);
    };

    const onPaste = (e: ClipboardEvent) => {
        if (!props.onPaste) {
            return;
        }

        const value = e.clipboardData?.getData("text");
        props.onPaste(value);
    };

    return (
        <input
            ref={el}
            class="cm-pin-field"
            max-length="1"
            autocomplete="off"
            type={type()}
            disabled={props.disabled}
            inputmode={inputMode()}
            pattern={props.type === "numeric" ? "[0-9]*" : "^[a-zA-Z0-9]+$"}
            onKeyDown={onKeyDown}
            onInput={onChange}
            value={value()}
            autofocus={autoFocus()}
            onPaste={onPaste}
        />
    );
}
